package com.moon.interface_api.utils;


import javax.net.ssl.*;
import java.io.*;
import java.net.*;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 *Created by chengliang on 2018/11/26.
 * 用于请求伪装ip地址，ip地址是不可控的
 */
public class IPProxyUtils {


    /**
     *@Author:chengliang
     *@date 2018/11/23_17:19
     *@param
     *@return 代理的ip地址
     */
    public static String getProxyIP() {
        String ipport = "";
        try {
            String order = "39a9c3c944bc7dc103a9870e263c6b0a";
            java.net.URL url = new java.net.URL("http://api.ip.data5u.com/dynamic/get.html?order="
                    + order + "&ttl&random=true");

            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setConnectTimeout(3000);
            connection = (HttpURLConnection) url.openConnection();

            InputStream raw = connection.getInputStream();
            InputStream in = new BufferedInputStream(raw);
            byte[] data = new byte[in.available()];
            int bytesRead = 0;
            int offset = 0;
            while (offset < data.length) {
                bytesRead = in.read(data, offset, data.length - offset);
                if (bytesRead == -1) {
                    break;
                }
                offset += bytesRead;
            }
            in.close();
            raw.close();
            String[] res = new String(data, "UTF-8").split("\n");
            System.out.println(">>>>>>>>>>>>>>当前返回IP量 " + res.length);
            for (String ip : res) {
                System.out.println(">>>>>>>>>>>>>>当前返回IP " + ip);
                ipport = ip;
            }
        } catch (Exception e) {
            System.err.println(">>>>>>>>>>>>>>获取IP出错, " + e.getMessage());
        }
        return ipport;
    }

    /**
     *@Author:chengliang
     *@date 2018/11/23_17:20
     *@param headers 头
     *@param method post  get
     *@param urlPath 目标
     *@param data 请求数据   aa=b&c=d
     *@param ipport ip地址
     *@return 响应，
     */
    public static String requestForproxy(String method, String urlPath,
                                         HashMap<String, String> headers, String data, String ipport) {

        HttpURLConnection connection = null;
        try {
            URL link = new URL(urlPath);

            String charset = "UTF-8";

            // 设置代理IP
            String[] split = ipport.split(",");
            if (split != null && split.length >= 1) {
                ipport = split[0];
            }
            String[] strs = ipport.split(":");
            if (strs != null && strs.length >= 2) {
                Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(strs[0],
                        Integer.parseInt(strs[1])));
                connection = (HttpURLConnection) link.openConnection(proxy);
            }else{
                connection = (HttpURLConnection) link.openConnection();
            }

        } catch (NumberFormatException e1) {
            e1.printStackTrace();
        } catch (MalformedURLException e1) {
            e1.printStackTrace();
        } catch (IOException e1) {
            e1.printStackTrace();
        }

        // 处理SSL证书问题

        try {
            SSLSocketFactory oldSocketFactory = null;
            HostnameVerifier oldHostnameVerifier = null;

            boolean useHttps = urlPath.startsWith("https");
            if (useHttps) {
                HttpsURLConnection https = (HttpsURLConnection) connection;
                oldSocketFactory = trustAllHosts(https);
                oldHostnameVerifier = https.getHostnameVerifier();
                https.setHostnameVerifier(DO_NOT_VERIFY);
            }
        } catch (Exception e) {
            System.err.println("添加证书信任出错：" + e.getMessage());
        }
        try {
            connection.setDoInput(true);
            connection.setRequestMethod(method);
            if (headers != null && headers.size() > 0) {
                Iterator<String> iterator = headers.keySet().iterator();
                while (iterator.hasNext()) {
                    String key = iterator.next();
                    String values = headers.get(key);
                    connection.setRequestProperty(key, values);
                }
            }
            connection.setConnectTimeout(60 * 1000);
            connection.setReadTimeout(60 * 1000);
            PrintWriter out = null;
            // post参数
            if (data != null) {
                connection.setDoOutput(true);
                OutputStream outStream = connection.getOutputStream();
                outStream.write(data.getBytes("UTF-8"));
                outStream.flush();
                outStream.close();
            }
            // 读取响应信息
            InputStreamReader reader =null;
            BufferedReader reader2 =null;
            reader = new InputStreamReader(connection.getInputStream(),"utf-8");
            reader2 = new BufferedReader(reader);
            String string = reader2.readLine();
            System.out.println("服务端响应的结果"+string);
            return string;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (connection != null) {
                connection.disconnect();
            }
        }

        return "请求异常";
    }

    /**
     * 信任所有
     * @param connection
     * @return
     */
    private static SSLSocketFactory trustAllHosts(HttpsURLConnection connection) {
        SSLSocketFactory oldFactory = connection.getSSLSocketFactory();
        try {
            SSLContext sc = SSLContext.getInstance("TLS");
            sc.init(null, trustAllCerts, new java.security.SecureRandom());
            SSLSocketFactory newFactory = sc.getSocketFactory();
            connection.setSSLSocketFactory(newFactory);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return oldFactory;
    }
    /**
     * 覆盖java默认的证书验证
     */
    private static final TrustManager[] trustAllCerts = new TrustManager[]{new X509TrustManager() {
        public java.security.cert.X509Certificate[] getAcceptedIssuers() {
            return new java.security.cert.X509Certificate[]{};
        }

        public void checkClientTrusted(X509Certificate[] chain, String authType)
                throws CertificateException {
        }

        public void checkServerTrusted(X509Certificate[] chain, String authType)
                throws CertificateException {
        }
    }};

    /**
     * 设置不验证主机
     */
    private static final HostnameVerifier DO_NOT_VERIFY = new HostnameVerifier() {
        public boolean verify(String hostname, SSLSession session) {
            return true;
        }
    };

    public static void main(String[] args){
        Map<String, String> header = new HashMap<>();
        header.put("Content-Type","application/json");
        String get = requestForproxy("POST", "http://flow.hjriches.com/user/sendCode", (HashMap<String, String>) header, "{\"phone\":\"18621818995\",\"type\":\"login\"}", "117.191.11.71:80");
        System.out.println(get);
    }
}
